package cn.itsource;

import org.springframework.amqp.core.*;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

//RabbitMQ配置： 包含了生产者和消费者的配置
@Configuration
public class RabbitmqConfig {

    //交换机名字
    public static final String EXCHANGE_TOPICS_INFORM = "exchange_topics_inform";
    //队列：邮箱
    public static final String QUEUE_INFORM_EMAIL = "queue_inform_email";
    //队列：短信
    public static final String QUEUE_INFORM_SMS = "queue_inform_sms";

    //tipic
    //1.生产者创建交换机
    @Bean(EXCHANGE_TOPICS_INFORM) //在Spring中bean的名字
    public Exchange exchangeTopicsInform() {
        //durable(true)持久化，消息队列重启后交换机仍然存在 ：在mq中交换机的名字
        return ExchangeBuilder.topicExchange(EXCHANGE_TOPICS_INFORM).durable(true).build();
    }

    //2.消费创建队列

    //声明队列:短信
    @Bean(QUEUE_INFORM_SMS)
    public Queue queueInformSMS() {
        Queue queue = new Queue(QUEUE_INFORM_SMS,true);
        return queue;
    }

    //声明队列:邮箱
    @Bean(QUEUE_INFORM_EMAIL)
    public Queue queueInformEmail() {
        Queue queue = new Queue(QUEUE_INFORM_EMAIL,true);
        return queue;
    }

    //3.消费者把队列绑定到交换机
    /**
     * channel.queueBind(INFORM_QUEUE_SMS,"inform_exchange_topic","inform.#.sms.#");
     * 绑定队列到交换机 .
     *
     * @param queue    the queue
     * @param exchange the exchange
     * @return the binding
     */
    @Bean
    public Binding bindingQueueInformSMS() {
        return BindingBuilder.bind(queueInformSMS()).to(exchangeTopicsInform()).with("sms.*").noargs();
    }

    @Bean
    public Binding bindingQueueInformEmail(@Qualifier(QUEUE_INFORM_EMAIL) Queue queue,
                                              @Qualifier(EXCHANGE_TOPICS_INFORM) Exchange exchange) {
        return BindingBuilder.bind(queue).to(exchange).with("email.*").noargs();
    }
}
